<template>
  <a-modal
    width="1100px"
    centered
    destroyOnClose
    :maskClosable="false"
    :visible="visible"
    :title="title"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form layout="inline">
      <a-form-item label="选择类型">
        <a-radio-group :options="options" v-model="form.dispatchType" />
      </a-form-item>
      <br />
      <a-form-item label="提箱类型">
        <a-radio-group
          :options="optionsNew"
          v-model="form.dispatchEmptyOrHeavy"
          @change="onChangeEoh"
        />
      </a-form-item>
      <br />
      <a-form-item v-if="!type3">
        <a-radio-group :default-value="value2" @change="onChange2">
          <a-radio-button v-for="op in options2" :key="op.value" :value="op.value">{{op.label}}</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <p v-if="type3">改派车辆：</p>
      <br />
      <div
        v-if="!localData"
        style="border: 1px solid #e2e2e2; padding: 15px; margin: 10px 0; border-radius: 4px;"
      >
        <a-form-item label="类型">
          <a-select v-model="searchForm.isSelfOperation" class="selectWidth">
            <a-select-option key>全部</a-select-option>
            <a-select-option v-for="v in SelfOperationOptions" :key="v.key">{{v.title}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="车牌号">
          <a-input v-model="searchForm.truckNumber" :max-length="20"></a-input>
        </a-form-item>
        <a-form-item label="所属车队">
          <a-input v-model="searchForm.custName" :max-length="20"></a-input>
        </a-form-item>
        <a-form-item label="司机姓名">
          <a-input v-model="searchForm.driverName" :max-length="20"></a-input>
        </a-form-item>
        <a-form-item label="手机号码">
          <a-input v-model="searchForm.phone" :max-length="20"></a-input>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSubmit1">查询</a-button>
        </a-form-item>
      </div>
    </a-form>

    <a-row>
      <a-col v-if="!type3" :span="24" style="margin: 10px 0">
        <a-button v-if="value2===1" type="primary" @click="cancelBatch()">取消指派</a-button>
        <a-button v-if="value2===2" type="primary" @click="doBatch()">批量指派</a-button>
      </a-col>
      <a-col v-if="!localData" :span="24">
        <a-table
          :row-selection="type3 ? null : { selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
          :columns="columns"
          :data-source="tableData"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
          rowKey="tractorId"
        >
          <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
          <template slot="opt" slot-scope="text, record">
            <a-button
              v-if="!type3&&value2===1"
              type="primary"
              size="small"
              @click="cancelBatch([record])"
            >取消</a-button>
            <a-button
              v-if="!type3&&value2===2"
              type="primary"
              size="small"
              @click="doBatch([record])"
            >指派</a-button>
            <a-button
              v-if="type3&&record.isSelect !== 1"
              :disabled="currentSelectItem && record.tractorId === currentSelectItem.tractorId"
              type="primary"
              size="small"
              @click="doAssignOnly(record)"
            >指派</a-button>
          </template>
        </a-table>
      </a-col>
      <a-col v-if="localData" :span="24">
        <a-table
          :columns="columnsLocal"
          :data-source="tableData"
          rowKey="tractorId"
          :pagination="paginationLocal"
        >
          <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
          <template slot="opt" slot-scope="text, record">
            <a-button type="primary" size="small" @click="cancelBatch([record])">取消</a-button>
          </template>
        </a-table>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { queryAssignTruckList, orderTruckDispatchBatch, queryTruckOrderDispatchInfo } from '@/api/landCenter'
import { SelfOperationOptions } from '../options'

const defaultForm = (type = 1, atype = 2, orderTruckId = '', orderTruckIds = '') => {
  return {
    type, // 1、待派单 2待接单指派 3待接单改派 待出发改派、运输中改派
    atype, // 1、当前指派车辆 2待指派车辆 type=2时传
    orderTruckId, // 订单id type=2、3时传
    orderTruckIds, // 订单id type=2、3时传
    isSelfOperation: '', // 车辆类型自营：1是，0否
    truckNumber: '', // 牵引车/挂车车牌号
    custName: '', // 所属车队
    driverName: '', // 司机姓名
    phone: '', // 手机号码
    sort: 1 // 箱量排序 0倒序 1正序
  }
}

const defaultSaveForm = () => {
  return {
    type: '', // 1待派单批量指派 2待接单改派 3司机待出发
    orderTruckId: '', // 订单id
    orderTruckIds: '', // 订单id
    dispatchType: 1, // 派单类型：1提箱离港、2空车离港、3套箱接单
    dispatchEmptyOrHeavy: 1, // 1空，2重
    dispatchList: [] // 指派车辆列表
  }
}

const options = [
  { label: '提箱离港', value: 1 },
  { label: '空车离港', value: 2 },
  { label: '套箱接单', value: 3 }
]
const optionsNew = [
  { label: '空箱', value: 1 },
  { label: '重箱', value: 2 }
]

export default {
  props: {
    visible: Boolean,
    type: {
      type: String,
      validator: function (value) {
        // 这个值必须匹配下列字符串中的一个
        return ['ASSIGN', 'RE_ASSIGN', 'BATCH_ASSIGN'].indexOf(value) !== -1
      }
    },
    order: Object
  },
  data () {
    const columns = [
      {
        title: '序号',
        width: 60,
        customRender: (text, record, index) => {
          if (record.isSelect === 1) {
            return <div>{index + 1}<span class='redMsg'>当前指派</span></div>
          }
          return index + 1
        }
      },
      {
        title: '车辆',
        dataIndex: 'tractorNumber',
        width: 200,
        customRender: (text, record, index) => {
          if (record.trailerNumber) {
            return `${text}·${record.trailerNumber}`
          }
          return text
        }
      },
      {
        title: '司机姓名',
        dataIndex: 'driverName'
      },
      {
        title: '手机号码',
        dataIndex: 'phone'
      },
      {
        title: '类型',
        dataIndex: 'isSelfOperation',
        width: 70,
        customRender: (text) => {
          if (text === 1) {
            return '自营'
          } else if (text === 0) {
            return '外派'
          }
        }
      },
      {
        title: '车队',
        dataIndex: 'custName',
        ellipsis: true
      },
      {
        title: '今日箱量(个)',
        dataIndex: 'containerNum',
        sorter: true
      },
      {
        title: '操作',
        width: 90,
        scopedSlots: { customRender: 'opt' }
      }
    ]

    const columnsLocal = [
      {
        title: '序号',
        width: 60,
        customRender: (text, record, index) => {
          if (record.isSelect === 1) {
            return <div>{index + 1}<span class='redMsg'>当前指派</span></div>
          }
          return index + 1
        }
      },
      {
        title: '车辆',
        width: 200,
        dataIndex: 'tractorNumber',
        customRender: (text, record, index) => {
          if (record.trailerNumber) {
            return `${text}·${record.trailerNumber}`
          }
          return text
        }
      },
      {
        title: '司机姓名',
        dataIndex: 'driverName'
      },
      {
        title: '手机号码',
        dataIndex: 'phone'
      },
      {
        title: '类型',
        width: 70,
        dataIndex: 'isSelfOperation',
        customRender: (text) => {
          if (text === 1) {
            return '自营'
          } else if (text === 0) {
            return '外派'
          }
        }
      },
      {
        title: '车队',
        dataIndex: 'custName',
        ellipsis: true
      },
      {
        title: '今日箱量(个)',
        dataIndex: 'containerNum',
        sorter: (a, b) => a.containerNum - b.containerNum
      },
      {
        title: '操作',
        width: 90,
        scopedSlots: { customRender: 'opt' }
      }
    ]

    return {
      SelfOperationOptions,
      value: 1,
      options: [...options],
      optionsNew: [...optionsNew],
      value2: 2,
      options2: [
        { label: '当前指派车辆', value: 1 },
        { label: '待指派车辆', value: 2 }
      ],
      searchForm: defaultForm(),
      addTractors: [], // 新指派车辆ids type=1、2时传
      deleteTractors: [], // 取消指派车辆ids type=3时传
      columns,
      columnsLocal,
      tableData: [],
      loading: false,
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      selectedRowKeys: [],
      selectedRows: [],
      form: defaultSaveForm(),
      currentSelectItem: {} // 改派：当前指派的车辆
    }
  },
  computed: {
    title () {
      return this.type === 'ASSIGN' ? '指派' : (this.type === 'RE_ASSIGN' ? '改派' : (this.type === 'BATCH_ASSIGN' ? '批量指派' : ''))
    },
    type3 () {
      return this.searchForm.type === 3
    },
    type2 () {
      return this.searchForm.type === 2
    },
    localData () {
      return this.order.status === 2 && this.value2 === 1
    }
  },
  methods: {
    onChange2 (e) {
      this.value2 = e.target.value
      this.searchForm = defaultForm(this.searchForm.type, e.target.value, this.form.orderTruckId, this.form.orderTruckIds)
      this.handleSubmit1()
    },
    handleTableChange (pagination, filters, sorter) {
      if (sorter.order === 'descend') {
        this.searchForm.sort = 0
      } else if (sorter.order === 'ascend') {
        this.searchForm.sort = 1
      } else {
        this.searchForm.sort = ''
      }
      this.handleSubmit()
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.selectedRowKeys = []
      this.selectedRows = []

      if (this.order.status === 2 && this.value2 === 1) { // 待派单，取本地数据
        this.tableData = this.addTractors
        this.paginationLocal = {
          pageSize: 10,
          total: this.addTractors.length,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第1/${Math.ceil(total / 10)}页`
        }
      } else {
        this.loading = true
        const addTractorIds = this.addTractors.map(v => v.tractorId).join(',')
        const deleteTractorIds = this.deleteTractors.map(v => v.tractorId).join(',')
        queryAssignTruckList({
          ...this.searchForm,
          addTractorIds,
          deleteTractorIds,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }).then(rsp => {
          this.loading = false
          this.tableData = rsp.data.list
          if (this.type3) {
            this.currentSelectItem = rsp.data.list.filter(v => v.isSelect === 1)[0]
          }
          this.pagination = {
            current: this.pageNum,
            pageSize: rsp.data.pageSize,
            total: rsp.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              // this.handleSubmit()
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              // this.handleSubmit()
            }
          }
        }).catch(() => { this.loading = false })
      }
    },
    cancelBatch (itemArr) {
      const selecteds = itemArr || this.selectedRowKeys
      if (selecteds.length > 0) {
        this.deleteTractors = this.deleteTractors.concat(selecteds)
        this.addTractors = this.addTractors.filter(v => !selecteds.filter(w => w.tractorId === v.tractorId)[0])
        this.handleSubmit()
      } else {
        this.$message.error('请选择车辆')
      }
    },
    doBatch (itemArr) {
      const selecteds = itemArr || this.selectedRows
      if (selecteds.length > 0) {
        this.addTractors = this.addTractors.concat(selecteds)
        this.deleteTractors = this.deleteTractors.filter(v => !selecteds.filter(w => w.tractorId === v.tractorId)[0])
        this.handleSubmit()
      } else {
        this.$message.error('请选择车辆')
      }
    },
    doAssignOnly (item) { // 改派页面
      this.currentSelectItem = { ...item }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getCheckboxProps: record => ({
      props: {
        disabled: record.isSelect === 1,
        checked: record.isSelect === 1
      }
    }),
    handleOk () {
      this.confirmLoading = true
      let dispatchList = []
      if (this.type3) {
        dispatchList = [{
          'driverId': this.currentSelectItem.driverId,
          'tractorId': this.currentSelectItem.tractorId,
          'trailerId': this.currentSelectItem.trailerId
        }]
      } else {
        dispatchList = this.addTractors.map(v => ({
          'driverId': v.driverId,
          'tractorId': v.tractorId,
          'trailerId': v.trailerId
        }))
      }
      if (dispatchList.length === 0) {
        this.$message.error('请先选择指派车辆！')
        this.confirmLoading = false
        return false
      }
      this.form.dispatchList = dispatchList
      orderTruckDispatchBatch(this.form).then(rsp => {
        this.confirmLoading = false
        this.$message.success('指派成功')
        this.$emit('setAssignVisible', true)
      }).catch(() => { this.confirmLoading = false })
    },
    handleCancel () {
      this.$emit('setAssignVisible')
    },
    onChangeEoh (e) {
      const _this = this
      if (e.target.value === 2) {
        this.$confirm({
          title: '切换至重箱，APP端无法输入箱号封号，确定切换吗？',
          onCancel () {
            _this.form.dispatchEmptyOrHeavy = 1
          }
        })
      } else if (e.target.value === 1) {
        this.$confirm({
          title: '切换至空箱，APP端可变更箱号封号，确定切换吗？',
          onCancel () {
            _this.form.dispatchEmptyOrHeavy = 2
          }
        })
      }
    }
  },
  watch: {
    visible () {
      if (this.visible) {
        this.options = [...options]
        this.optionsNew = [...optionsNew]
        // 选择类型 初始化
        this.value = 1

        this.form = defaultSaveForm()
        this.addTractors = []
        this.deleteTractors = []

        const status = this.order.status // status 2待派单、3司机待接单、4司机待出发 5运输中
        // 查询 条件初始化 type 1、待派单 2司机待接单指派 3司机待接单改派 待出发改派、运输中改派
        let type = 1
        if (status === 3 && this.type === 'ASSIGN') {
          type = 2
          this.options = this.options.filter(v => v.value === this.order.dispatchType)
          this.optionsNew = this.optionsNew.filter(v => v.value === (this.order.dispatchEmptyOrHeavy || 1))
        } else if ((status === 3 && this.type === 'RE_ASSIGN') || status === 4 || status === 5) {
          type = 3
        }

        let atype
        this.value2 = 2
        if (status === 3) { // 司机待接单默认先展示当前指派车辆列表
          this.value2 = 1
          atype = 1
        }

        // 保存 数据初始化： 1待派单批量 2待接单 3司机待出发 4运输中
        if (status === 2) this.form.type = 1
        else if (status === 3) this.form.type = 2
        else if (status === 4) this.form.type = 3
        else if (status === 5) this.form.type = 4

        if (this.form.type !== 1) {
          this.form.orderTruckId = this.order.orderTruckIds
        }

        this.form.orderTruckIds = this.order.orderTruckIds

        this.form.dispatchType = this.order.dispatchType || 1
        this.form.dispatchEmptyOrHeavy = this.order.dispatchEmptyOrHeavy || 1

        if (this.form.type !== 1) {
          queryTruckOrderDispatchInfo({ orderTruckId: this.form.orderTruckId }).then(rsp => {
            this.form.dispatchType = rsp.data.dispatchType
            this.form.dispatchEmptyOrHeavy = rsp.data.dispatchEmptyOrHeavy
          })
        }

        this.searchForm = defaultForm(type, atype, this.form.orderTruckId, this.form.orderTruckIds)
        this.handleSubmit()

        if (this.type2) {
          queryAssignTruckList({
            ...this.searchForm,
            pageNum: 1,
            pageSize: 999
          }).then(rsp => {
            this.addTractors = rsp.data.list
          })
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ td {
  position: relative;
  .redMsg {
    position: absolute;
    display: inline-block;
    background: red;
    top: 0;
    width: 60px;
    left: 0;
    font-size: 12px;
    height: 16px;
    text-align: center;
    color: white;
  }
}
</style>
